{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 数据预处理方法\n",
    "本文总结的是我们大家在python中常见的数据预处理方法，以下通过sklearn的preprocessing模块来介绍;\n",
    "\n",
    "1. 标准化（Standardization or Mean Removal and Variance Scaling)\n",
    "\n",
    "变换后各维特征有0均值，单位方差。也叫z-score规范化（零均值规范化）。计算方式是将特征值减去均值，除以标准差。\n",
    "\n",
    "`sklearn.preprocessing.scale(X)`\n",
    "一般会把train和test集放在一起做标准化，或者在train集上做标准化后，用同样的标准化器去标准化test集，此时可以用scaler\n",
    "```\n",
    "scaler = sklearn.preprocessing.StandardScaler().fit(train)\n",
    "scaler.transform(train)\n",
    "scaler.transform(test)\n",
    "```\n",
    "实际应用中，需要做特征标准化的常见情景：SVM\n",
    "\n",
    "2. 最小-最大规范化\n",
    "\n",
    "最小-最大规范化对原始数据进行线性变换，变换到[0,1]区间（也可以是其他固定最小最大值的区间）\n",
    "\n",
    "```\n",
    "min_max_scaler = sklearn.preprocessing.MinMaxScaler()\n",
    "min_max_scaler.fit_transform(X_train)\n",
    "\n",
    "```\n",
    "3.规范化（Normalization）\n",
    "\n",
    "规范化是将不同变化范围的值映射到相同的固定范围，常见的是[0,1]，此时也称为归一化。\n",
    "\n",
    "将每个样本变换成unit norm。\n",
    "```\n",
    "X = [[ 1, -1, 2],[ 2, 0, 0], [ 0, 1, -1]]\n",
    "sklearn.preprocessing.normalize(X, norm='l2')\n",
    "```\n",
    "得到：\n",
    "`array([[ 0.40, -0.40, 0.81], [ 1, 0, 0], [ 0, 0.70, -0.70]])`\n",
    "\n",
    "可以发现对于每一个样本都有，0.4^2+0.4^2+0.81^2=1,这就是L2 norm，变换后每个样本的各维特征的平方和为1。类似地，L1 norm则是变换后每个样本的各维特征的绝对值和为1。还有max norm，则是将每个样本的各维特征除以该样本各维特征的最大值。\n",
    "在度量样本之间相似性时，如果使用的是二次型kernel，需要做Normalization\n",
    "\n",
    "4. 特征二值化（Binarization）\n",
    "\n",
    "给定阈值，将特征转换为0/1\n",
    "```\n",
    "binarizer = sklearn.preprocessing.Binarizer(threshold=1.1)\n",
    "binarizer.transform(X)\n",
    "\n",
    "```\n",
    "5. 标签二值化（Label binarization）\n",
    "\n",
    "```\n",
    "lb = sklearn.preprocessing.LabelBinarizer()\n",
    "```\n",
    "\n",
    "6. 类别特征编码\n",
    "\n",
    "有时候特征是类别型的，而一些算法的输入必须是数值型，此时需要对其编码。\n",
    "```\n",
    "enc = preprocessing.OneHotEncoder()\n",
    "enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])\n",
    "enc.transform([[0, 1, 3]]).toarray() #array([[ 1., 0., 0., 1., 0., 0., 0., 0., 1.]])\n",
    "```\n",
    "\n",
    "上面这个例子，第一维特征有两种值0和1，用两位去编码。第二维用三位，第三维用四位。\n",
    "\n",
    "另一种编码方式\n",
    "```\n",
    "newdf=pd.get_dummies(df,columns=[\"gender\",\"title\"],dummy_na=True)\n",
    "```\n",
    "\n",
    "7.标签编码（Label encoding）\n",
    "```\n",
    "le = sklearn.preprocessing.LabelEncoder()\n",
    "le.fit([1, 2, 2, 6])\n",
    "le.transform([1, 1, 2, 6]) #array([0, 0, 1, 2])\n",
    "#非数值型转化为数值型\n",
    "le.fit([\"paris\", \"paris\", \"tokyo\", \"amsterdam\"])\n",
    "le.transform([\"tokyo\", \"tokyo\", \"paris\"]) #array([2, 2, 1])\n",
    "```\n",
    "\n",
    "8.特征中含异常值时\n",
    "\n",
    "`sklearn.preprocessing.robust_scale`\n",
    "\n",
    "9.生成多项式特征\n",
    "\n",
    "这个其实涉及到特征工程了，多项式特征/交叉特征。\n",
    "\n",
    "```python\n",
    "poly = sklearn.preprocessing.PolynomialFeatures(2)\n",
    "poly.fit_transform(X)\n",
    "```\n",
    "原始特征：\n",
    "\n",
    "转化后：\n",
    "\n",
    "总结\n",
    "\n",
    "以上就是为大家总结的python中常用的九种预处理方法分享，希望这篇文章对大家学习或者使用python能有一定的帮助，如果有疑问大家可以留言交流。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
